<template>
    <div class="water-bill-container">
        <!-- 月度水费卡片 -->
        <el-card class="bill-card">
            <div class="header">
                <div class="left-controls">
                    <div class="year-selector">
                        <el-select v-model="currentYear" @change="handleYearChange" size="small">
                            <el-option v-for="year in availableYears" :key="year" :label="`${year}年`" :value="year" />
                        </el-select>
                    </div>

                    <div class="year-compare">
                        <el-checkbox v-model="showCompare" @change="updateChartOptions">
                            年度对比
                        </el-checkbox>
                    </div>
                </div>

                <div class="title">
                    <div class="title-label">
                        {{ currentYear }}
                    </div>
                    年各月份实缴水费
                </div>

                <div class="total-amount">
                    本年度已累计费用：{{ calculateYearTotal(currentYear) }} 元
                </div>

                <!-- 添加编辑按钮 -->
                <div class="actions">
                    <el-button type="primary" size="small" @click="openEditDialog">
                        编辑实缴记录
                    </el-button>
                </div>
            </div>

            <!-- 月度水费图表 (添加v-if重新渲染) -->
            <div v-loading="isChartLoading" class="chart-wrapper">
                <BaseChart v-if="!isChartLoading" :options="monthlyChartOptions" />
            </div>
        </el-card>

        <!-- 历史水费卡片 -->
        <el-card class="bill-card">
            <div class="chart-title">历史年实缴水费</div>
            <div v-loading="isYearlyChartLoading" class="chart-wrapper">
                <BaseChart v-if="!isYearlyChartLoading" :options="yearlyChartOptions" />
            </div>
        </el-card>

        <!-- 编辑实缴记录对话框 -->
        <el-dialog title="编辑实缴记录" v-model="editDialogVisible" width="500px" @close="handleDialogClose">
            <div class="edit-form">
                <div class="edit-title">{{ currentYear }}
                    年实缴记录
                </div>

                <div v-for="(month, index) in months" :key="index" class="edit-item">
                    <div class="month-label">{{ currentYear }}-{{ index + 1 }}</div>
                    <el-input v-model.number="editData[index]" type="number" placeholder="请输入金额" class="amount-input">
                        <template slot="append">元</template>
                    </el-input>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEditData">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import BaseChart from '../../../../../components/chart/BaseChart.vue';

// 年份和水费数据
const waterBillData = ref({
    2022: {
        monthlyData: [80, 95, 85, 100, 80, 90, 100, 110, 90, 95, 85, 90],
        yearlyTotal: 1200
    },
    2023: {
        monthlyData: [85, 100, 90, 105, 85, 95, 95, 100, 80, 90, 75, 100],
        yearlyTotal: 1100
    },
    2024: {
        monthlyData: [85, 105, 90, 110, 85, 95, 90, 105, 85, 100, 80, 95],
        yearlyTotal: 1300
    },
    2025: {
        monthlyData: [102, 125, null, null, null, null, null, null, null, null, null, null],
        yearlyTotal: 22841
    }
});

// 当前年份和对比状态
const currentYear = ref(2025);
const showCompare = ref(true);
const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

// 添加加载状态变量
const isChartLoading = ref(false);
const isYearlyChartLoading = ref(false);

// 编辑对话框相关变量
const editDialogVisible = ref(false);
const editData = ref([]);

// 打开编辑对话框
const openEditDialog = () => {
    // 复制当前年份的数据到编辑数据中
    editData.value = [...(waterBillData.value[currentYear.value]?.monthlyData || Array(12).fill(null))];
    editDialogVisible.value = true;
};

// 处理对话框关闭
const handleDialogClose = () => {
    // 清空编辑数据
    editData.value = [];
};

// 保存编辑数据
const saveEditData = () => {
    // 更新当前年份的数据
    if (!waterBillData.value[currentYear.value]) {
        waterBillData.value[currentYear.value] = {
            monthlyData: Array(12).fill(null),
            yearlyTotal: 0
        };
    }

    // 更新月度数据
    waterBillData.value[currentYear.value].monthlyData = [...editData.value];

    // 重新计算年度总额
    waterBillData.value[currentYear.value].yearlyTotal = calculateYearTotal(currentYear.value);

    // 更新图表
    updateChartOptions();
    updateYearlyChartOptions();

    // 关闭对话框
    editDialogVisible.value = false;

    // 提示保存成功
    ElMessage({
        message: '实缴记录保存成功',
        type: 'success'
    });
};

// 可用年份列表
const availableYears = computed(() => {
    return Object.keys(waterBillData.value).map(Number).sort((a, b) => b - a);
});

// 计算年度总费用
const calculateYearTotal = (year) => {
    const yearData = waterBillData.value[year]?.monthlyData || [];
    return yearData.reduce((sum, value) => sum + (value || 0), 0);
};

// 月度图表配置
const monthlyChartOptions = ref({
    xAxisData: months,
    yAxisUnit: '元',
    series: [],
    customColors: ['#909399', '#409EFF'],
    showMarkLine: true
});

// 历史年度图表配置
const yearlyChartOptions = ref({
    xAxisData: [],
    yAxisUnit: '元',
    series: [
        {
            name: '年度水费',
            type: 'bar',
            data: []
        }
    ],
    customColors: ['#409EFF'],
    isStacked: false
});

// 更新月度图表配置 - 添加加载效果
const updateChartOptions = () => {
    // 设置加载状态为 true (隐藏图表)
    isChartLoading.value = true;

    // 准备当前年度数据
    const currentYearData = waterBillData.value[currentYear.value]?.monthlyData || Array(12).fill(null);

    // 基础系列配置
    let series = [
        {
            name: `${currentYear.value}年`,
            type: 'bar',
            data: currentYearData,
        }
    ];

    // 如果开启了年度对比，添加上一年数据
    if (showCompare.value) {
        const prevYear = currentYear.value - 1;
        if (waterBillData.value[prevYear]) {
            series = [
                {
                    name: `${prevYear}年`,
                    type: 'bar',
                    data: waterBillData.value[prevYear].monthlyData,
                },
                ...series
            ];
        }
    }

    // 更新图表配置
    monthlyChartOptions.value = {
        ...monthlyChartOptions.value,
        series
    };

    // 使用 setTimeout 延迟显示图表，模拟加载效果
    setTimeout(() => {
        isChartLoading.value = false;
    }, 100); // 100毫秒的加载效果
};

// 更新年度图表配置 - 添加加载效果
const updateYearlyChartOptions = () => {
    // 设置加载状态为 true
    isYearlyChartLoading.value = true;

    const years = Object.keys(waterBillData.value).map(Number).sort();
    const values = years.map(year => {
        // 为当前年添加标记
        const isCurrentYear = year === new Date().getFullYear();
        return {
            value: waterBillData.value[year].yearlyTotal,
            // 添加标签
            label: {
                show: isCurrentYear,
                position: 'top',
                formatter: isCurrentYear ? '累计中' : '',
                fontSize: 12,
                color: '#666'
            }
        };
    });

    yearlyChartOptions.value = {
        ...yearlyChartOptions.value,
        xAxisData: years.map(String),
        series: [
            {
                name: '年度水费',
                type: 'bar',
                data: values
            }
        ]
    };

    // 延迟显示图表
    setTimeout(() => {
        isYearlyChartLoading.value = false;
    }, 100);
};

// 处理年份变化
const handleYearChange = () => {
    updateChartOptions();
};

// 添加对比状态变化的监听
watch(showCompare, () => {
    updateChartOptions();
});

// 初始化
onMounted(() => {
    updateChartOptions();
    updateYearlyChartOptions();
});
</script>

<style scoped>
.water-bill-container {
    width: 100%;
    margin: 0 auto;
    padding: var(--gap-normal);
}

.bill-card {
    margin-bottom: var(--gap-normal);
}

.header {
    display: flex;
    align-items: center;
    margin-bottom: var(--gap-normal);
    flex-wrap: wrap;
}

.left-controls {
    display: flex;
    align-items: center;
}

.year-selector {
    width: 8rem;
    margin-right: var(--gap-normal);
}

.year-compare {
    margin-right: var(--gap-normal);
}

.title {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: var(--gap-small);
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin: 0 var(--gap-normal);
}

.title-label {
    background-color: #44ABFF;
    color: #fff;
    padding: 2px 4px;
    border-radius: 5px;

}


.total-amount {
    color: #606266;
    font-size: 14px;
    margin-right: var(--gap-normal);
}

.actions {
    margin-left: auto;
}

.chart-title {
    text-align: center;
    margin: var(--gap-normal);
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}

/* 添加图表容器和加载样式 */
.chart-wrapper {
    height: 250px;
}

/* 编辑表单样式 */
.edit-form {
    max-height: 500px;
    overflow-y: auto;
    padding-right: 10px;
}

.edit-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    text-align: center;
}

.edit-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.month-label {
    width: 80px;
    flex-shrink: 0;
}

.amount-input {
    flex-grow: 1;
}
</style>